<template>
<div class="icons" :class="{'search-fixed':isFixed}">
  <BannerInDetail :isShowSearch="true" :categoryList="categoryList" @toPosition="toPosition" />
  <!-- start svg图标组 -->
  <section class="svgs">
    <div class="svgs-inner">
      <el-card class="box-card">
        <div slot="header">
          <span class="card-title">remixicon</span>
          <!-- <a href="https://remixicon.com/" target="_blank"><el-button style="float: right; padding: 3px 0" type="text" icon="el-icon-s-promotion">查看官网</el-button></a> -->
        </div>
        <!-- <el-row v-for="(value,key,index) in iconList" :key="index">
          123
        </el-row> -->
        <el-row v-for="(value,key,index) in iconList" :key="index">
          <el-col :span="24">
            <el-divider :id="key">{{key}}</el-divider>
          </el-col>
          <el-col :span="3" v-for="(item,i) in value" :key="i">
            <div class="icon" @click="open(item)">
              <svg-icon class="svg-icon" :icon-class="item.name" style="width:2em;height:2em;margin-bottom: 16px;"/>
              <!-- <object id="map" type="image/svg+xml" :data="item.file_url|getStaticIcon" width="32" height="32" style="opacity: 0.5;
                    margin-bottom: 16px;"></object> -->
              <!-- <img :src="item.file_url|getStaticIcon" :alt="item.name"> -->
              <p style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{item.name}}</p>
            </div>
          </el-col>
        </el-row>
        <el-dialog
          :visible.sync="dialogVisible"
          width="700px;"
          >
          <div class="top">
            <div class="dialog_icon">
              <div id="svg" style="width:240px;height:240px;"></div>
              <!-- <embed id="embed" :src="icon.file_url|getStaticIcon" width="80" height="80" type="image/svg+xml" pluginspage="http://www.adobe.com/svg/viewer/install/" /> -->
              <!-- <embed id="embed" src="../assets/icons/Communication/chat-1-fill.svg" width="80" height="80" type="image/svg+xml" pluginspage="http://www.adobe.com/svg/viewer/install/" /> -->
              <!-- <img class="svg" src="../assets/icons/Communication/chat-1-fill.svg" alt=""> -->
              <!-- <object id="svg-sample" src="../assets/icons/Communication/chat-1-fill.svg"></object> -->
            </div>
            <div class="top_right">
              <div class="name_add">
                <div class="name">{{icon.name}}</div>
                <i class="el-icon-folder-add" @click="toFavorites(icon.id)" style="font-size:18px;"></i>
              </div>
              <div class="copy_icon">
                <el-button style="width:100%">
                  &lt;i class="{{icon.name}}"&gt;&lt;/i&gt; 
                </el-button>
                <el-button @click="doCopy()">copy</el-button>
              </div>  
            </div>
          </div>
          <el-divider></el-divider> 
          <div class="block">
            <el-color-picker v-model="color1" @active-change="change" :predefine="colorArr"></el-color-picker>
            <el-divider direction="vertical"></el-divider>
            <el-select allow-create filterable v-model="size" placeholder="大小" @change="changSize">
              <el-option
                :border="false"
                v-for="item in sizeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-divider direction="vertical"></el-divider>
            
            <el-button slot="reference" @click="visible = !visible,openSvgCopy()"><i class="el-icon-folder-add"></i> Copy SVG</el-button>
           
            
            <el-divider direction="vertical"></el-divider>
            <el-button @click="downloadPng()"><i class="el-icon-download"></i>png</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button @click="downloadSvg"><i class="el-icon-download"></i>svg</el-button>
          </div>
           <div class="svg_copy" v-if="visible">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="SVG file" name="svg_file">
                  <div class="svg_inner">{{svgFile}}</div>
                </el-tab-pane>
                <el-tab-pane label="DataURL" name="data_url">DataURL</el-tab-pane>
              </el-tabs>
              <el-button class="copy_btn" @click="copy_svg()">copy</el-button>
            </div>
          <!-- <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
          </span> -->
        </el-dialog>

      </el-card>
    </div>
  </section>
  <!-- end svg图标组 -->
</div>
</template>

<script>
import BannerInDetail from '@/components/BannerInDetail.vue'

export default {
  name: 'icons',
  layout: 'main',
  components: {
    BannerInDetail,
  },
  data() {
    return {
      copy_use:'',
      file_url:'',
      svgName:'',
      svgFile:'',
      activeName:"svg_file",
      visible:false,
      itemName:'',
      colorArr:["#000","#fff","#E74C3C","#E67E22","#F1C40E","#2FCC71","#19BC9B","#3298DB","#9B59B6","#ECF0F1","#95A4A6","#34485E"],
      categoryList:[],
      originalList:[],//原始icon列表
      iconList:[],//分类后的列表
      icon:{
        name:"",
        file_url:''
      },
      size:'',
      sizeList: [{
          value: 12,
          label: '12px'
        }, {
          value: 16,
          label: '16px'
        }, {
          value: 18,
          label: '18px'
        }, {
          value: 24,
          label: '24px'
        }, {
          value: 32,
          label: '32px'
        }, {
          value: 36,
          label: '36px'
        }, {
          value: 48,
          label: '48px'
        }, {
          value: 64,
          label: '64px'
        }, {
          value: 72,
          label: '72px'
        }, {
          value: 96,
          label: '96px'
        },{
          value: 120,
          label: '120px'
        },{
          value: 240,
          label: '240px'
        }],
      color1:'#606266',
      dialogVisible:false,
      isFixed: false, //默认让搜索栏固定的，滚动超出100px时要求固定在浏览器视口上方
    }
  },
      
  methods: {
    toFavorites(id) {
      if (window.sessionStorage.getItem("tuyibo_userid") !== null) {
        var data = JSON.parse(window.sessionStorage.getItem("tuyibo_userid"));
        this.$axios.post("/api/web/favoritesIcon", {
            uid: data.userid,
            icon_id: id
          }).then(res => {
            if (res.data.code == -1) {
              this.$message.info(res.data.msg);
            } else {
              this.$message.success(res.data.msg);
            }
          }).catch(err => {
            console.log(err);
          });
      } else if( window.loginbox ){
        window.loginbox.show = true
      }
    },
    // toCollect(){
    //   var favorites_list=JSON.parse(localStorage.getItem('favorites_list'))
    //   if(!favorites_list){
    //     let list=[this.svgName]
    //     localStorage.setItem('favorites_list',JSON.stringify(list));
    //   }else{
    //     var index=favorites_list.indexOf(this.svgName)
    //     if(index<0){
    //       favorites_list.push(this.svgName)
    //       localStorage.setItem('favorites_list',JSON.stringify(favorites_list));
    //     }else{
    //       favorites_list.splice(index, 1)
    //       localStorage.setItem('favorites_list',JSON.stringify(favorites_list));
    //     }
    //   }
    // },
    copy_svg(){
      this.$copyText(this.svgFile).then(e=> {
        this.$message.success("复制成功!")
      },  (e)=>{
        this.$message.error("复制失败!")
        console.log(e)
      })
    },
    dataProcessing () {
      this.copy_use= `<i class="${this.svgName}"></i> `
    },
    doCopy(){
      this.dataProcessing()
      this.$copyText(this.copy_use).then(e=> {
        this.$message.success("复制成功!")
      },  (e)=>{
        this.$message.error("复制失败!")
        console.log(e)
      })
    },
    downloadPng(){
      var svg=document.getElementById("svg").getElementsByTagName('svg')[0]
      let width = svg.getBoundingClientRect().width;
      let height =svg.getBoundingClientRect().height;
      var serializer = new XMLSerializer();
      var source = '<?xml version="1.0" standalone="no"?>\r\n'+serializer.serializeToString(svg);
      var image = new Image();
      image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source);
      var canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      var context = canvas.getContext("2d")
      image.onload = ()=>{
        context.drawImage(image, 0, 0);

        var a = document.createElement("a");
        a.download = this.svgName+".png";
        a.href = canvas.toDataURL('image/png');
        a.click();
      }
    },
    openSvgCopy(){
      console.log("132")
    },
    changSize(v){
      var svg=document.getElementById("svg").getElementsByTagName('svg')[0]
      svg.setAttribute("width", v);
      svg.setAttribute("height", v);
      this.svgFile=document.getElementById("svg").innerHTML.replace(" vertical-align: middle;",'');
    },
    change(v){
      this.color1=v
      var svg=document.getElementById("svg").getElementsByTagName('svg')[0]
      svg.style.fill=v;
      this.svgFile=document.getElementById("svg").innerHTML.replace(" vertical-align: middle;",'');
    },
    toPosition(v){
      var dom=document.querySelector(`#${v}`)
      function heightToTop(ele){
        let root = document.body;
        let height = 0;
        do{
            height += ele.offsetTop;
            ele = ele.offsetParent;
        }while( ele !== root )
        return height;
      }
      window.scrollTo({
        top:heightToTop(dom)-200,
        behavior:'smooth'
      })
    },
    open(item){
      this.svgName=item.name
      this.file_url=item.file_url
      Object.assign(this.icon, item);
      this.dialogVisible = true;
      this.$axios.get('/icons/'+item.file_url)
      .then(res=>{
        var html= res.data
        var div=document.getElementById("svg");
        div.innerHTML=html;
        var svg=div.childNodes[0]
        this.svgFile=div.innerHTML
        // svg.setAttribute("style", "fill:" + this.color1);
        svg.style.fill=this.color1;
        svg.style.verticalAlign="middle"
        if(this.size){
          svg.setAttribute("width",this.size)
          svg.setAttribute("height",this.size)
        }
      })
    },
    getIconList(keywords=null){
      this.$axios.post("/api/web/getIconList",{keywords})
      .then(res=>{
        var row=res.data
        this.originalList=res.data
        this.iconList=this.Consolidate(row);
        this.categoryList=Object.keys(this.iconList)
      })
    },
    // 整合数据
    Consolidate(row){
      var list={}
      for(let i in row){
        row[i].category=row[i].file_url.split("/")[0]
        if(list[row[i].category]===undefined){
          list[row[i].category]=[]
        }
        list[row[i].category].push(row[i])
      }
      return list;
    },
    //搜索icon
    searchIcons(keywords) {
      keywords=keywords.trim()
      var iconList = this.originalList;
      var results = keywords? iconList.filter(this.createFilter(keywords)) : iconList;
      this.iconList=this.Consolidate(results);
      this.categoryList=Object.keys(this.iconList)
    },
    createFilter(queryString){
      return list => {
        return (
          list.name.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
          ||list.file_url.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    downloadSvg(){
      var svg=document.getElementById("svg").getElementsByTagName('svg')[0]
      var serializer=new XMLSerializer();
      var source=serializer.serializeToString(svg);
      if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
          source=source.replace(/^<svg/,'<svg xmlns="http://www.w3.org/2000/svg"');
      }
      // if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
      //     source=source.replace(/^<svg/,'<svg xmlns="http://www.w3.org/1999/xlink"');
      // }
      source='<?xml version="1.0" standalone="no"?>\r\n'+source;
      this.saveFile(source,this.svgName+".svg")
    },
    saveFile (data, filename) {
        var a=document.createElementNS("http://www.w3.org/1999/xhtml","a");
        var blob=new Blob([data]);
        var objectURL=URL.createObjectURL(blob);
        a.href=objectURL;
        a.download=filename;
        var e=document.createEvent("MouseEvents");
        e.initMouseEvent("click",true,false,window,0,0,0,0,0,false,false,false,false,0,null);
        a.dispatchEvent(e)
    },
    handleScroll() { //顶部的导航栏在滚动的时候监听，如果滚动距离超过60px，就给导航栏header追加一个class=isFixed
      const top = document.documentElement.scrollTop;
      if (top > 24) {
        this.isFixed = true;
      } else {
        this.isFixed = false
      }
    },
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll)
    this.getIconList()
  },
  // 离开该页面需要移除这个监听的事件
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.icons {
    min-height: 800px;
    .banner {
        margin-bottom: 48px;
        position: relative;
        top: 0;
        z-index: 150;
    }
    &.search-fixed {
        padding-top: 230px;
        .banner {
            width: 100%;
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            transition: all 2.2s;
        }
    }
    .svgs {
        margin-bottom: 24px;
        .svgs-inner {
            max-width: 1380px;
            margin: 0 auto;
            padding: 0 16px;
            .icon {
              margin: 0 auto;
              text-align: center;
              padding: 16px;
              &:hover {
                  background-color: @color-global-bg-color;
              }
              .svg-icon{
                color: @color-regular;
              }
              > img {
                  width: 32px;
                  height: 32px;
                  opacity: 0.5;
                  margin-bottom: 16px;
              }
            }
            .el-dialog{
              width: 700px;
              margin-top:8vh!important;
              .top{
                display: flex;
                .dialog_icon{
                  #svg{
                    position: relative;
                    border: 1px solid #ddd;
                    margin-right: 24px;
                    line-height: 240px;
                    text-align: center;
                    overflow: hidden;
                    vertical-align:  middle;
                    svg{
                      vertical-align: middle;
                    }
                  }
                  >img{
                    width: 32px;
                    height: 32px;
                    opacity: 0.5;
                  }
                }
                .top_right{
                  width: 100%;
                  display: flex;
                  flex-direction: column;
                  justify-content: space-around;
                  .name_add{
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .name{
                      font: 18px bold;
                    }
                  }
                  .copy_icon{
                    display: flex;
                    justify-content: space-between;
                    white-space:nowrap;
                  }
                }
              }
              .block{
                display: flex;
                align-items: center;
                justify-content: space-between;
                flex-wrap: nowrap;
              }
              .svg_copy{
                overflow: hidden;
                padding: 30px 20px;
                background: #fff;
                border-radius: 0 0 2px 2px;
                position: fixed;
                top: 630px;
                left:50%;
                margin-top: -150px;
                margin-left: -350px;
                z-index: 2007;
                width: 700px;
                height: 300px;
                .svg_inner{
                  height: 146px;
                  overflow: auto;
                }
                .copy_btn{
                  position: absolute;
                  right: 20px;
                  bottom: 30px;
                }
              }
            }
        }
    }
}
</style>
